import Vue from 'vue';
import VueRouter from 'vue-router';
import { Dialog } from 'vant';
import store from '@/store/';

Vue.use(VueRouter);
// 路由规则
const routes = [
	{
		path:'/login',
		name:'login',
		component:()=>import('../views/Login/index'),
		meta:{requiresAuth:false}//添加额外的自定义数据
	},
	{
		path:'/',
		component:()=>import('../views/layout/Layout'),
		children:[
			{
				path:'/',
				component:()=>import('../views/home/Home'),
				meta:{requiresAuth:false}
			},
			{
				path:'/qa',
				component:()=>import('../views/QA/qa'),
				meta:{requiresAuth:false}
			},
			{
				path:'/video',
				component:()=>import('../views/video/Video'),
				meta:{requiresAuth:false}
			},
			{
				path:'/my',
				component:()=>import('../views/my/My'),
				meta:{requiresAuth:false}
			} 
		]
	},{
		path:'/search',
		name:'search',
		component:()=>import('../views/search/'),
		meta:{requiresAuth:false}
	},{
		path:'/article/:articleId',
		name:'article',
		component:()=>import('../views/article/'),
		//将动态路由参数映射到组件的props中，无论是访问还是维护性都很方便
		props:true,
		meta:{requiresAuth:false}
	},
	{
		path:'/user/profile',
		name:'user-profile',
		component:()=>import('@/views/user-profile'),
		meta:{requiresAuth:false}
	},
	{
		path:'/user/chat',
		name:'user-chat',
		component:()=>import('@/views/user-chat'),
		meta:{requiresAuth:true}
	}
];

// 实例化路由
const router = new VueRouter({
  routes
});
// to:需访问的首页路由信息
// from:来自那个页面的路由信息
// next:放行的标记
router.beforeEach((to,from,next) => {
	if(to.meta.requiresAuth){
		//如果已登录，则直接通过
		if(store.state.user){
			return next();
		}
		
		//没有登录，提示是否登录
		Dialog.confirm({
			title:'访问提示',
			message:'该功能需要登录才能访问，确定登录吗'
		}).then(()=>{//确认执行这里
		  next('login');
		}).catch(()=>{//取消执行这里
		 //取消了，中断路由导航
			next(false);
		});
	}else{
		///不需要登录状态的页面，直接过去
	   next();
	   }
});

// 暴露路由
export default router;
